package cn.tedu.service.impl;

import cn.tedu.dao.GoodsDao;
import cn.tedu.dao.SaleDao;
import cn.tedu.domain.Goods;
import cn.tedu.domain.Sale;
import cn.tedu.excep.NotEnoughException;
import cn.tedu.service.BuyGoodsService;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class BuyGoodsServiceImpl implements BuyGoodsService{
    private GoodsDao goodsDao;
    private SaleDao saleDao;
    public void setGoodsDao(GoodsDao goodsDao) {
        this.goodsDao = goodsDao;
    }

    public void setSaleDao(SaleDao saleDao) {
        this.saleDao = saleDao;
    }


    @Transactional(
            propagation = Propagation.REQUIRED,
            isolation = Isolation.DEFAULT,
            readOnly = false,
            rollbackFor = {
                    NullPointerException.class,NotEnoughException.class
            }
    )//这些属性传播行为、隔离级别都是默认的，可以直接添加注解，事务回滚出发的默认是方法发生运行时异常RuntimeException
    @Override
    public void buy(Integer goodsID, Integer nums) {
        System.out.println("===buy方法的开始===");
        //记录销售信息，向sale表中添加记录
        Sale Newsale = new Sale();
        Newsale.setGid(goodsID);
        Newsale.setNums(nums);
        saleDao.insertSale(Newsale);

        //更新goods表中的库存信息
        Goods goods = goodsDao.selectGoods(goodsID);
        if (goods==null){
            //购买商品不存在
            throw new NullPointerException("编号为："+goodsID+"的商品不存在");
        }else if (goods.getAmount()<nums){
            //购买商品库存不足
            throw new NotEnoughException("编号为："+goodsID+"的商品库存不足啦");
        }else {
            //把传入的参数赋值给一个对象，在传入更新goods表库存的方法
            Goods buyGoods = new Goods();
            buyGoods.setId(goodsID);
            buyGoods.setAmount(nums);
            goodsDao.updateGoods(buyGoods);
            System.out.println("===buy方法的结束===");
        }


    }



    public static void main(String[] args) throws ParseException {
        int a=0;
        int b=0;
        String date="2019-1-10,,,2019-3-1,2018-7-31,2018-12-5,,2019-6-13";
        String[] dateStr = date.split(",");
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        ArrayList<Date> dateArrayList = new ArrayList<>();
        for (String s : dateStr) {
            if (s.equals("")){
                dateArrayList.add(null);
            }else {
                Date parse = sf.parse(s);
                dateArrayList.add(parse);
            }
        }
        for (Date date1 : dateArrayList) {
            if (date1==null){
                a++;
            }
            b++;
        }
        System.out.println(a+"/"+b);

    }


}
